package com.jaks.xpense;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jaks.xpense.data.Tags;
import com.jaks.xpense.data.entities.TableEntity;
import com.jaks.xpense.data.entities.Tag;

public class EditTagActivity extends Activity {

	private Tags tags;
	private EditText tagText;
	private long id;
	private int order;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.edittag);

		id = 0;
		order = 0;
		tags = new Tags(this);
		tagText = (EditText) findViewById(R.id.tagText);
		tagText.setFilters(new InputFilter[] { filter });

		TextView save = (TextView) findViewById(R.id.saveTag);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			id = extras.getLong(TableEntity.Id);
			setTitle(R.string.editTag);
		} else {
			setTitle(R.string.newTag);
		}

		populate();

		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String name = tagText.getText().toString();
				if (name.trim().length() == 0)
					return;

				if (!save(name)) {
					Toast.makeText(EditTagActivity.this, R.string.tagExists, Toast.LENGTH_SHORT).show();
					return;
				}

				finish();
			}
		});
	}

	private void populate() {
		if (id == 0)
			return;

		Tag tag = (Tag) tags.read(id);
		order = tag.getOrder();
		tagText.setText(tag.getName());
	}

	private boolean save(String name) {

		long existingId = tags.getId(name);

		if (id == 0) {
			if (existingId > 0)
				return false;

			long createdId = tags.create(new Tag(name));
			if (createdId > 0) {
				id = createdId;
			}
		} else {

			if (existingId > 0) {
				if (id != existingId)
					return false;
			} else
				tags.update(new Tag(id, order, name));
		}

		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		tags.close();
	}

	private final InputFilter filter = new InputFilter() {

		@Override
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
		    int dend) {

			for (int index = start; index < end; index++) {
				if (source.charAt(index) == ':') {
					return "";
				}
			}
			return null;
		}
	};
}
